package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class FileUploadController {

    @RequestMapping(value = "/fileupload")
    //参数中定义MultipartFile参数，用于接收页面提交的type=file类型的表单，要求表单名称与参数名相同
    public String fileupload(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws IOException {
        for (MultipartFile file : files) {
            if (!file.isEmpty()){
                //获取上传的文件名称
                String oldFileName = file.getOriginalFilename();
                //设置存储路径
                String realPath = request.getServletContext().getRealPath("images");

                if (!new File(realPath).exists()){
                    new File(realPath).mkdirs();
                }
                //获取上传文件的后缀
//            System.out.println(fileName.lastIndexOf("."));
//            System.out.println(fileName.substring(4));
                String suffixName = oldFileName.substring(oldFileName.lastIndexOf("."));
                //uuid 拼接 suffixName
                String fileName = UUID.randomUUID().toString().replaceAll("-","")+suffixName;
//            System.out.println(fileName);

                file.transferTo(new File(realPath,fileName));
            }

        }
//        System.out.println(file.getBytes().length+"占用的硬盘空间");
//        System.out.println(file.getContentType()+"类别");
//        System.out.println(file.getName()+"方法参数名称");
//        System.out.println(file.getOriginalFilename()+"文件名称");
//        System.out.println(file.getSize()+"占用的硬盘空间"); //占用的硬盘空间
//        System.out.println(file.isEmpty());
//        System.out.println("file upload is running ..."+ file);
//        file.transferTo(new File("abc.png"));
/*        if (!file.isEmpty()){
            //获取上传的文件名称
            String oldFileName = file.getOriginalFilename();
            //设置存储路径
            String realPath = request.getServletContext().getRealPath("images");

            if (!new File(realPath).exists()){
                 new File(realPath).mkdirs();
            }
            //获取上传文件的后缀
//            System.out.println(fileName.lastIndexOf("."));
//            System.out.println(fileName.substring(4));
            String suffixName = oldFileName.substring(oldFileName.lastIndexOf("."));
            //uuid 拼接 suffixName
            String fileName = UUID.randomUUID().toString().replaceAll("-","")+suffixName;
//            System.out.println(fileName);

            file.transferTo(new File(realPath,fileName));
        }*/



        return "page.jsp";
    }
}
